package servlet;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import pojo.Book;
import pojo.Customer;
import service.BookManager;
import service.CartManager;
import service.impl.BookManagerFactory;
import service.impl.CartManagerFactory;

public class CartServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	private BookManager bookManager = BookManagerFactory.INSTANCE;
	private CartManager cartManager = CartManagerFactory.INSTANCE;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Customer c = (Customer) request.getSession().getAttribute("customer");
		Map<String, Integer> userCart = cartManager.getCart().get(c.getId());
		Map<Book, Integer> books = new HashMap<>();
		
		if (userCart != null) {
			for (Map.Entry<String, Integer> e : userCart.entrySet()) {
				Book b = bookManager.loadBook(e.getKey());
				books.put(b, e.getValue());
			}
		}
		
		request.setAttribute("books", books);
		request.getRequestDispatcher("../WEB-INF/views/cart.jsp").forward(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
